using System.Collections.Immutable;
using System.Diagnostics;
using DimensionsHelper.LanguageService.Symbols;
using DimensionsHelper.LanguageService.Syntax;

namespace DimensionsHelper.LanguageService;

public class AnalysisCategorical : AnalysisExpression
{
    private readonly List<AnalysisCategory> _categories = [];

    internal AnalysisCategorical(CategoricalLiteral source, AnalysisNode? parent) :
        base(AnalysisBoundKinds.Literal, source, parent)
    {
        foreach (CategoryLiteral? category in source)
        {
            _categories.Add(new AnalysisCategory(category, this));
        }
    }


    public override int ChildrenCount => _categories.Count;


    public override AnalysisExpression? WithImplicitlyConversion(ValueTypeSymbol targetType)
    {
        if (targetType == ValueTypeSymbol.Any || targetType == ValueTypeSymbol.Categorical ||
            targetType == ValueTypeSymbol.Null)
        {
            return this;
        }

        if (targetType == ValueTypeSymbol.Boolean)
        {
            return new AnalysisBoolean(NodeConverter.ToBoolean((CategoricalLiteral)Syntax, ChildrenCount > 0),
                Parent).WithContainingWithSymbol(GetContainingWithSymbol());
        }

        return null;
    }

    public override IEnumerable<AnalysisNode> GetChildren()
    {
        return _categories.ToImmutableArray();
    }

    internal override void AddChild(AnalysisNode child)
    {
        Debug.Assert(child.Syntax.IsNode(SyntaxKinds.Category));
        child.Parent = this;
        _categories.Add((AnalysisCategory)child);
    }
}

public static partial class AnalysisNodeFactory
{
    /// <summary>
    /// 创建一个分类常量表达式
    /// </summary>
    /// <param name="source">原始语法节点</param>
    /// <param name="parent">父节点，可以忽略</param>
    public static AnalysisCategorical Categorical(CategoricalLiteral source, AnalysisNode? parent)
    {
        AnalysisCategorical categorical = new(source, parent);
        categorical.Bind(ValueTypeSymbol.Categorical);
        return categorical;
    }
}